package com.fifth.apartment.config;

import cn.hutool.json.JSONUtil;
import com.fifth.apartment.result.Result;
import com.fifth.apartment.utils.WebUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class SecurityHandler {

    //认证失败
    @Bean
    public AuthenticationEntryPoint authenticationEntryPoint(){
        return new AuthenticationEntryPoint() {
            @Override
            public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
                Result result = new Result(false,"401认证失败");
                String json = JSONUtil.toJsonStr(result);
                //将字符串渲染到前端
                WebUtils.renderString(response,json);
            }
        };
    }

    @Bean
    public AccessDeniedHandler accessDeniedHandler(){
        return new AccessDeniedHandler() {
            @Override
            public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
                Result result = new Result(false, "403您的权限不足!");
                String json = JSONUtil.toJsonStr(result);
                // 将字符串渲染到客户端
                WebUtils.renderString(response, json);
            }
        };
    }
}
